<?php

use com\gdl\kq\dataobject\adminstatistics\AdminStatisticsDTO;
use com\gdl\common\dataobject\common\ResultDO;
use com\gdl\kq\interfaces\AttAdminStatisticsServiceIf;
/**
 *  考勤
 *  @author gdl
 */
class api_AttAdminStatisticsService extends api_Abstract implements AttAdminStatisticsServiceIf
{
    //统计接口
    public function statisticsAdminUserParticularInfos(AdminStatisticsDTO $AdminStatisticsDTO){

        $data = $AdminStatisticsDTO->data ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->data) :[];
        $platformId = $AdminStatisticsDTO->platformId ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->platformId) :0;

        #接受参数

        $unitId    = $data['unitId']?$data['unitId']:0;
        $unitIds    = $data['unitIds']?$data['unitIds']:0;
        $memberIds = $data['memberIds']?$data['memberIds']:0;
        $offset    = $data['offset']?$data['offset']:0;
        $num       = $data['num']?$data['num']:10;
        $date       = $data['date']?$data['date']:0;
        $adminUserId = $data['adminUserId']?$data['adminUserId']:0;

        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        $result->counts = 0;
        if(empty($platformId)){$result->message = "参数不正确"; return $result;}

        try{
            $userStatisticsInfos = [];
            $memberModel            = new model_attendance_member();
            $attendancerecordModel  = new model_attendance_attendancerecord();
            $attendancegroupModel   = new model_attendance_attendancegroup();
            $serviceUserModel       = new service_user();
            $serviceGlobalsModel    = new service_globals();
            $groupmemberrecordModel    = new model_attendance_groupmemberrecord();
            $approvalprocessleaverecordModel    = new model_attendance_approvalprocessleaverecord();

            //获取当前平台的组织架构和考勤用户的关联数组
            $UnitsList = $serviceUserModel->getMemberUnitsRelation($platformId,$adminUserId,2);

            if ($UnitsList){
                $UnitsList = $serviceGlobalsModel->setArrKeyId($UnitsList['relation']);
            }
//            print_r(json_encode($UnitsList));die;
            //查询该平台下所有人员
            $memberleftJoin = array('atd_position as `ap`' => '`ap`.id=atd_member.positionId');
            $memberCondition = " atd_member.platformId = {$platformId} and atd_member.status=2 ";
            if ($memberIds){
                $memberCondition .= " and atd_member.id in ($memberIds) ";
            }
            if ($unitIds){
                if (is_array($unitIds)){
                    $unitIds = implode(',',$unitIds);
                }
                $memberCondition .= " and atd_member.unitId in ($unitIds) ";
            }
            #分页
            if($offset=='0') $offset=1;
            $limit = ($offset - 1) * $num . "," . $num;
            $group = 'order by atd_member.id desc limit '.$limit;

            $userLists = $memberModel->select(
                $memberCondition,
                'atd_member.*,ap.title positionName',
                $group,
                '',
                $memberleftJoin
            )->items;
            $count = $memberModel->selectOne(
                $memberCondition,
                'count(*) num',
                "",
                '',
                $memberleftJoin
            );
            $count = $count?$count['num']:0;
            if ($userLists){
                $arrayDate = [];
                //传递日期是否为空
                if (empty($date)){//获取当月数据
                    $startDateTime = date('Y-m-01',time());  //获取本月第一天日期
                    $endDateTime   = date('Y-m-d', strtotime("$startDateTime +1 month -1 day"));//获取本月最后一天日期
                    $beginThismonth = mktime(0,0,0,date('m'),1,date('Y'));
                    $endThismonth   = mktime(23,59,59,date('m'),date('t'),date('Y'));
                    $datetime1 = date_create($startDateTime);
                    $datetime2 = date_create($endDateTime);
                    $interval = date_diff($datetime1, $datetime2);

                    $dateNum = $interval->format('%a')+1;

                    for($i=0;$i<$dateNum;$i++) {
                        $arrayDate[] = date('Y-m-d',$beginThismonth+$i*86400); //每隔一天赋值给数组
                    }
                }else{
                    $date = explode(' ',$date);
                    $startDateTime = $date[0];
                    $endDateTime = $date[1];
                    if ($startDateTime==$endDateTime){
                        $beginThismonth = strtotime($startDateTime);
                        $endThismonth = $beginThismonth;
                        $dateNum = 1;
                        for($i=0;$i<$dateNum;$i++) {
                            $arrayDate[] = date('Y-m-d',$beginThismonth+$i*86400); //每隔一天赋值给数组
                        }
                    }else{
                        $beginThismonth = strtotime($startDateTime);
                        $endThismonth = strtotime($endDateTime)+16*60*60-1;
                        $datetime1 = date_create($startDateTime);
                        $datetime2 = date_create($endDateTime);
                        $interval = date_diff($datetime1, $datetime2);
                        $dateNum = $interval->format('%a')+1;
                        for($i=0;$i<$dateNum;$i++) {
                            $arrayDate[] = date('Y-m-d',$beginThismonth+$i*86400); //每隔一天赋值给数组
                        }
                    }

                }

                //根据userid获取所有的考勤记录
                $userids = array_column($userLists,'id');
                $userids = implode(',',$userids);
                $attendancerecordCondition = "no<>2 and memberId in ($userids) and isDelete=0 and UNIX_TIMESTAMP(sureDate)>={$beginThismonth} and UNIX_TIMESTAMP(sureDate)<={$endThismonth}";
                $attendancerecordLists = $attendancerecordModel->select($attendancerecordCondition)->items;
                if ($attendancerecordLists){
                    $attendancerecordList = [];
                    foreach ($attendancerecordLists as $arLK=>$arlV){
                        $attendancerecordList[$arlV['memberId']][$arlV['sureDate']][] =  [
                            'id'=>$arlV['id'],
                            'leaveIn'=>$arlV['leaveIn'],
                            'leaveInId'=>$arlV['leaveInId'],
                            'no'=>$arlV['no'],
                            'clockinType'=>$arlV['clockinType'],
                            'clockinNum'=>$arlV['clockinNum'],
                            'clockinTime'=>$arlV['clockinTime'],
                        ];
                    }
                }else{
                    $attendancerecordList = [];
                }

                    //查询出平台下所有考勤组
//                    $attendancegroupList = $attendancegroupModel->select(" isDelete= 0 and platformId={$platformId}")->items;
//                    if ($attendancegroupList)$attendancegroupList = $serviceGlobalsModel->setArrKeyId($attendancegroupList);
                //考勤组权限限制
                $attendancegroup = "  atd_attendance_group.isDelete= 0 and atd_attendance_group.platformId={$platformId} and aagu.type=1 and aagu.type<>2";
                $appadminuser = new model_lhbase_appadminuser();
                $appadminuserInfo = $appadminuser->selectOne("id={$adminUserId} and characters='zg' and unitsId=0");
                if (!$appadminuserInfo){
                    $adminUserIdgroupId = new model_attendance_adminuserattendancegroup();
                    $attendancegroupIds = $adminUserIdgroupId->select(" adminUserId = {$adminUserId} ",'attendancegroupId')->items;

                    if ($attendancegroupIds){
                        $attendancegroupIds = array_column($attendancegroupIds,'attendancegroupId');
                        $attendancegroupIds = implode(',',$attendancegroupIds);
                        $attendancegroup .= " and atd_attendance_group.id in ({$attendancegroupIds}) ";
                    }else{
                        $result->message = "暂无数据";
                        $result->code = 200;
                        $result->data = [];
                        $result->counts = 0;
                        return $result;
                    }
                }

                    $userAttendancegroupJoin = array('atd_attendance_group_user as aagu' => 'aagu.agId=atd_attendance_group.id');
                    $userAttendancegroupList = $attendancegroupModel->select(
                        $attendancegroup,
                        'aagu.memberId id,aagu.agId,atd_attendance_group.title,atd_attendance_group.id agId',
                        '',
                        '',
                        $userAttendancegroupJoin
                    )->items;
                    if ($userAttendancegroupList)$userAttendancegroupList = $serviceGlobalsModel->setArrKeyId($userAttendancegroupList);

                    foreach ($userLists as $key=>$valus){
                        $userStatisticsInfos[$valus['id']]['id'] = $valus['id'];
                        $userStatisticsInfos[$valus['id']]['realName'] = $valus['realName'];
                        $userStatisticsInfos[$valus['id']]['positionName'] = $valus['positionName'];
                        $userStatisticsInfos[$valus['id']]['unitsName'] = isset($UnitsList[$valus['unitId']])?$UnitsList[$valus['unitId']]['title']:"";//@@
                        $userStatisticsInfos[$valus['id']]['upLevelNnitsName'] = (isset($UnitsList[$valus['unitId']]) && isset($UnitsList[$UnitsList[$valus['unitId']]['pid']]))?$UnitsList[$UnitsList[$valus['unitId']]['pid']]['title']:"本单位";
                        $userStatisticsInfos[$valus['id']]['attendanceGroupName'] = isset($userAttendancegroupList[$valus['id']])?$userAttendancegroupList[$valus['id']]['title']:"未添加考勤组";//@@
                        $userClockinList = isset($attendancerecordList[$valus['id']])?$attendancerecordList[$valus['id']]:'';

                        $userDateList = [];
                        //组装数据
                        foreach ($arrayDate as $dateKey=>$dateValue){
                            $startDateNowTime = strtotime($dateValue." 00:00:00");
                            $endDateNowTime = strtotime($dateValue." 23:59:59");
                            $undate = strtotime($dateValue);
                            //查询用户当天是否需要打卡 考勤组人员档案表 根据档案表查询历史配置
                            $groupmemberrecordInfo = $groupmemberrecordModel->selectOne("memberIds like '%{$valus['id']}%' and addTime<={$undate} order by id  desc");
                            if ($groupmemberrecordInfo){
                                $workdayKey = unserialize($groupmemberrecordInfo['workday']);

                                $holidayKey = $this->arrayDateToKey(unserialize($groupmemberrecordInfo['holiday']));
                                //特殊工作日定义 [2018-02-11?@(春节(补))','2018-02-11?@(清明节(补))','2018-02-11?@(春节(补))']
                                $specialWorkdayKey = $this->arrayDateToKey(unserialize($groupmemberrecordInfo['specialWorkday']));

                                //获取日期是否是休息日 bool false是节假日  true不是节假日
                                $isHolidaysAndFestivals = $serviceGlobalsModel->getDateIsHolidaysAndFestivals($dateValue,$workdayKey,$holidayKey,$specialWorkdayKey);

                                //查询用户当天是否有请假记录
                                $leaverecordList = $approvalprocessleaverecordModel->select(" memberId = {$valus['id']} and status= 2 and startTime>$startDateNowTime and endTime<$endDateNowTime")->items;

                                if ($leaverecordList){
                                    $leaveDate = [];
                                    $leaverecordType = array("事假","年假","事假","调休","产假","婚假","丧假");
                                    foreach ($leaverecordList as $leaverecordK=>$leaverecordV){
                                        $leaveDate[] = $leaverecordType[$leaverecordV['leaveType']]."从".date('Y-m-d H:s',$leaverecordV['startTime'])."到".date('Y-m-d H:s',$leaverecordV['endTime']);
                                    }
                                    $leaveDate = implode(',',$leaveDate);
                                }else{
                                    $leaveDate = "";
                                }
                                $upTime = [1=>'未打卡',2=>'未打卡',3=>'未打卡'];
                                $downTime = [1=>'未打卡',2=>'未打卡',3=>'未打卡'];
                                if (isset($userClockinList[$dateValue])){
                                    foreach ($userClockinList[$dateValue] as $clockinV){
                                        if ($clockinV['clockinType']==1 && $clockinV['clockinNum']==1){
                                            $upTime[1] = gmdate("H:i",$clockinV['clockinTime']);
                                        }elseif ($clockinV['clockinType']==1 && $clockinV['clockinNum']==2){
                                            $downTime[1] = gmdate("H:i",$clockinV['clockinTime']);
                                        }elseif ($clockinV['clockinType']==2 && $clockinV['clockinNum']==1){
                                            $upTime[2] = gmdate("H:i",$clockinV['clockinTime']);
                                        }elseif ($clockinV['clockinType']==2 && $clockinV['clockinNum']==2){
                                            $downTime[2] = gmdate("H:i",$clockinV['clockinTime']);
                                        }elseif ($clockinV['clockinType']==3 && $clockinV['clockinNum']==1){
                                            $upTime[3] = gmdate("H:i",$clockinV['clockinTime']);
                                        }elseif ($clockinV['clockinType']==3 && $clockinV['clockinNum']==2){
                                            $downTime[3] = gmdate("H:i",$clockinV['clockinTime']);
                                        }
                                    }
                                }
                            }else{
                                $isHolidaysAndFestivals = 1;
                                $upTime = [1=>'未打卡',2=>'未打卡',3=>'未打卡'];
                                $downTime = [1=>'未打卡',2=>'未打卡',3=>'未打卡'];
                                $leaveDate = "";
                            }

                            $userDateList[$dateValue] = [
                                'status'=>$isHolidaysAndFestivals?1:2,//1正常 2休息
                                'upTime'=>$upTime,
                                'downTime'=>$downTime,
                                'leaveDate'=>$leaveDate,
                            ];
                        }

                        //二次组装
                        $dateMod = [];
                        $upTime = [];
                        $downTime = [];
                        $leaveDate = [];
                        $weekarray = array("日","一","二","三","四","五","六"); //先定义一个数组
                        foreach ($userDateList as $ke=>$valu){
                            $dateMod[] = $ke."/星期".$weekarray[date("w",strtotime($ke))];
                            if ($valu['status']==2){
                                $upTime[] = [$ke,'休息中'];
                                $upTime[] = [$ke,'休息中'];
                                $upTime[] = [$ke,'休息中'];
                                $downTime[] = [$ke,'休息中'];
                                $downTime[] = [$ke,'休息中'];
                                $downTime[] = [$ke,'休息中'];
                            }else{
                                foreach ($valu['upTime'] as $kk=>$vv){
                                    $upTime[] = [$ke,$vv];
                                }
                                foreach ($valu['downTime'] as $kk=>$vv){
                                    $downTime[] = [$ke,$vv];
                                }
                            }
                            $leaveDate[] = [$ke,$valu['leaveDate']];
                        }


//                        $arrayDate = $arrayDate;
                        $userStatisticsInfos[$valus['id']]['dateMod'] = $dateMod;
                        $userStatisticsInfos[$valus['id']]['upTime'] = $upTime;
                        $userStatisticsInfos[$valus['id']]['downTime'] = $downTime;
                        $userStatisticsInfos[$valus['id']]['leaveDate'] = $leaveDate;
//                        $userStatisticsInfos[$valus['id']]['dateList'] = $userDateList;
//                        print_r(json_encode($dateMod));die;

                    }
//                    print_r(json_encode($userStatisticsInfos));die;
                $result->data = [[json_encode($userStatisticsInfos)]];
                $result->message ='成功';
                $result->code = 200;
                $result->counts = $count;
            }else{
                $result->data = [[]];
                $result->message ='成功';
                $result->code = 200;
                $result->counts = $count;
            }
        }catch(Exception $e){
            $result->code = 400;
            $result->message = '异常';
        }

        return $result;
    }

    //通过日期获取人员打卡详细
    public function getAdminUserClockinRecordByDate(AdminStatisticsDTO $AdminStatisticsDTO){
        $data = $AdminStatisticsDTO->data ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->data) : "";

        #接受参数

        $date = $data['date']?$data['date']:0;
        $userId = $data['userId']?$data['userId']:0;

        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        if(empty($userId)){$result->message = "请选择用户"; return $result;}
        if(empty($date)){$result->message = "请选择日期"; return $result;}

        try{
            $attendancerecordModel = new model_attendance_attendancerecord();
            $groupmemberrecordModel = new model_attendance_groupmemberrecord();
            $attendancegroupModel = new model_attendance_attendancegroup();
            $serviceGlobalsModel = new service_globals();
            $undate = strtotime($date);
            //查询用户当天是否需要打卡 考勤组人员档案表 根据档案表查询历史配置
            $groupmemberrecordInfo = $groupmemberrecordModel->selectOne("memberIds like '%{$userId}%' and addTime<={$undate} order by id  desc");
            if ($groupmemberrecordInfo) {
                $goDaysNum = unserialize($groupmemberrecordInfo['goDaysNum']);
                $num = count($goDaysNum);
            }else{
                $num = 0;
            }
            $returnList = [
                [
                    'clockinSureTime'=>'',
                    'clockinTime'=>'',
                    'type'=>"无记录",
//                    'address'=>'',
                    'remark'=>'',
                    'title'=>'',
                    'coordinate'=>[],
                    'coordinateR'=>[],
                    'deviation'=>'',
                    'photo'=>''
                ],[
                    'clockinSureTime'=>'',
                    'clockinTime'=>'',
                    'type'=>"无记录",
//                    'address'=>'',
                    'remark'=>'',
                    'title'=>'',
                    'coordinate'=>[],
                    'coordinateR'=>[],
                    'deviation'=>'',
                    'photo'=>''
                ],[
                    'clockinSureTime'=>'',
                    'clockinTime'=>'',
                    'type'=>"无记录",
//                    'address'=>'',
                    'remark'=>'',
                    'title'=>'',
                    'coordinate'=>[],
                    'coordinateR'=>[],
                    'deviation'=>'',
                    'photo'=>''
                ],[
                    'clockinSureTime'=>'',
                    'clockinTime'=>'',
                    'type'=>"无记录",
//                    'address'=>'',
                    'remark'=>'',
                    'title'=>'',
                    'coordinate'=>[],
                    'deviation'=>'',
                    'coordinateR'=>[],
                    'photo'=>''
                ],[
                    'clockinSureTime'=>'',
                    'clockinTime'=>'',
                    'type'=>"无记录",
//                    'address'=>'',
                    'remark'=>'',
                    'title'=>'',
                    'coordinate'=>[],
                    'deviation'=>'',
                    'coordinateR'=>[],
                    'photo'=>''
                ],[
                    'clockinSureTime'=>'',
                    'clockinTime'=>'',
                    'type'=>"无记录",
//                    'address'=>'',
                    'remark'=>'',
                    'title'=>'',
                    'coordinate'=>[],
                    'deviation'=>'',
                    'photo'=>'',
                    'coordinateR'=>[]
                ]
            ];
            switch ($num){
                case 0:
                    unset($returnList[5]);
                    unset($returnList[4]);
                    unset($returnList[3]);
                    unset($returnList[2]);
                    unset($returnList[1]);
                    unset($returnList[0]);
                    break;
                case 1:
                    unset($returnList[5]);
                    unset($returnList[4]);
                    unset($returnList[3]);
                    unset($returnList[2]);
                    break;
                case 2:
                    unset($returnList[5]);
                    unset($returnList[4]);
                    break;
            }
            $userrecordList  = $attendancerecordModel->select(" memberId = {$userId} and sureDate= '{$date}' and isDelete = 0")->items;

            foreach ($userrecordList as $clockinV){
                $type = "正常";
                if ($clockinV['abnormal']==1){//1 迟到 2 早退
                    $type = "迟到";
                }elseif ($clockinV['abnormal']==2){//1 迟到 2 早退
                    $type = "早退";
                }
                if ($clockinV['absenteeism']>=1){
                    $type = "旷工";
                }
                //1正常打卡 2缺卡 3补卡
                if ($clockinV['no']==2 || $clockinV['no']==3){//这个班次缺卡了或已经补卡
                    $type = $clockinV['no']==3?"补卡":"缺卡";
                }
                if ($clockinV['isGo']==2){//1正常考勤 2外勤打卡
                    $type .= ",外勤";
                }
                if ($clockinV['leaveIn']==2){//这个班次请假了
                    $type = "请假";
                }
                $address = !empty($clockinV['clockinCoordinate'])?unserialize($clockinV['clockinCoordinate']):'';
                $coordinateR = !empty($clockinV['coordinate'])?unserialize($clockinV['coordinate']):'';
                $data = [
                    'clockinSureTime'=>$clockinV['sureTime'],
                    'clockinTime'=>!empty($clockinV['clockinTime'])?date('Y-m-d H:i:s',$clockinV['clockinTime']):'',
                    'type'=>$type,
//                    'address'=>$address,
                    'remark'=>!empty($clockinV['remark'])?$clockinV['remark']:'',
                    'photo'=>!empty($clockinV['photo'])?$clockinV['photo']:'',
                    'title'=>!empty($address)?$address['title']:'',
                    'deviation'=>!empty($address)?$address['deviation']:'',
                    'coordinate'=>!empty($address)?$address['coordinate']:'',
                    'coordinateR'=>!empty($coordinateR)?$coordinateR:'',
                ];
                if ($clockinV['clockinType']==1 && $clockinV['clockinNum']==1){
                    $returnList[0] = $data;
                }elseif ($clockinV['clockinType']==1 && $clockinV['clockinNum']==2){
                    $returnList[1] = $data;
                }elseif ($clockinV['clockinType']==2 && $clockinV['clockinNum']==1){
                    $returnList[2] = $data;
                }elseif ($clockinV['clockinType']==2 && $clockinV['clockinNum']==2){
                    $returnList[3] = $data;
                }elseif ($clockinV['clockinType']==3 && $clockinV['clockinNum']==1){
                    $returnList[4] = $data;
                }elseif ($clockinV['clockinType']==3 && $clockinV['clockinNum']==2){
                    $returnList[5] = $data;
                }
            }
            $result->data = [[json_encode($returnList)]];
            $result->message ='成功';
            $result->code = 200;

        }catch(Exception $e){
            $result->message = '异常';
        }

        return $result;
    }

    //统计平台下的考勤接口
    public function getStatisticsPlatformClockin(AdminStatisticsDTO $AdminStatisticsDTO){

        $data = $AdminStatisticsDTO->data ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->data) :[];
        $platformId = $AdminStatisticsDTO->platformId ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->platformId) :0;

        #接受参数

        $date = $data['date']?$data['date']:0;
        $unitId    = $data['unitId']?$data['unitId']:0;
        $unitIds    = $data['unitIds']?$data['unitIds']:0;
        $agId    = $data['agId']?$data['agId']:0;
        $memberIds = $data['memberIds']?$data['memberIds']:0;
        $offset    = $data['offset']?$data['offset']:0;
        $num       = $data['num']?$data['num']:10;
        $adminUserId       = $data['adminUserId']?$data['adminUserId']:0;

        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        if(empty($platformId)){$result->message = "请选择平台"; return $result;}

        try{
            $recordings =  [
                'daysNum'=>0,//工作日天数
                'clockinNum'=>0,//考勤正常天数
                'late'=>0, //迟到
                'leavEarly'=>0,//早退
                'completion'=>0,//旷工 累计旷工时长
                'upMissCard'=>0,//上班缺卡次数
                'downMissCard'=>0,//下班缺卡次数
                'field'=>0,//外勤天数
                'leave'=>0,//请假
                'YearLeave'=>0,//年假
                'casualLeave'=>0,//事假
                'maternityLeave'=>0,//产假
                'maritalLeave'=>0,//婚假
                'funeralLeave'=>0,//丧假
                'nursingLeave'=>0,//护理假
            ];
            $userStatisticsInfos = [];
            $memberModel            = new model_attendance_member();
            $attendancerecordModel  = new model_attendance_attendancerecord();
            $attendancegroupModel   = new model_attendance_attendancegroup();
            $serviceUserModel       = new service_user();
            $serviceGlobalsModel    = new service_globals();
            $groupmemberrecordModel    = new model_attendance_groupmemberrecord();
            $approvalprocessleaverecordModel    = new model_attendance_approvalprocessleaverecord();

            //获取当前平台的组织架构和考勤用户的关联数组
            $UnitsList = $serviceUserModel->getMemberUnitsRelation($platformId,$adminUserId,2);

            if ($UnitsList){
                $UnitsList = $serviceGlobalsModel->setArrKeyId($UnitsList['relation']);
            }
//            print_r(json_encode($UnitsList));die;
            //查询该平台下所有人员
            $memberleftJoin = array('atd_position as `ap`' => '`ap`.id=atd_member.positionId');
            $memberCondition = " atd_member.platformId = {$platformId} and atd_member.status=2 ";
            if ($memberIds){
                $memberCondition .= " and atd_member.id in ($memberIds) ";
            }
            if ($unitIds){
                if (is_array($unitIds)){
                    $unitIds = implode(',',$unitIds);
                }
                $memberCondition .= " and atd_member.unitId in ($unitIds) ";
            }
            #分页
            if($offset=='0') $offset=1;
            $limit = ($offset - 1) * $num . "," . $num;
            $group = 'order by atd_member.id desc limit '.$limit;

            $userLists = $memberModel->select(
                $memberCondition,
                'atd_member.*,ap.title positionName',
                $group,
                '',
                $memberleftJoin
            )->items;
//            print_r($memberModel);die;
            $count = $memberModel->selectOne(
                $memberCondition,
                'count(*) num',
                "",
                '',
                $memberleftJoin
            );
            $count = $count?$count['num']:0;
            if ($userLists){
                $arrayDate = [];
                //传递日期是否为空
                if (empty($date)){//获取当月数据
                    $startDateTime = date('Y-m-01',time());  //获取本月第一天日期
                    $endDateTime   = date('Y-m-d', strtotime("$startDateTime +1 month -1 day"));//获取本月最后一天日期
                    $beginThismonth = mktime(0,0,0,date('m'),1,date('Y'));
                    $endThismonth   = mktime(23,59,59,date('m'),date('t'),date('Y'));
                    $datetime1 = date_create($startDateTime);
                    $datetime2 = date_create($endDateTime);
                    $interval = date_diff($datetime1, $datetime2);

                    $dateNum = $interval->format('%a')+1;

                    for($i=0;$i<$dateNum;$i++) {
                        $arrayDate[] = date('Y-m-d',$beginThismonth+$i*86400); //每隔一天赋值给数组
                    }
                }else{
                    $date = explode(' ',urldecode($date));
                    $startDateTime = $date[0];
                    $endDateTime = $date[1];
                    if ($startDateTime==$endDateTime){
                        $beginThismonth = strtotime($startDateTime." 00:00:00");
                        $endThismonth = strtotime($startDateTime." 23:59:59");
                        $dateNum = 1;
                        for($i=0;$i<$dateNum;$i++) {
                            $arrayDate[] = date('Y-m-d',$beginThismonth+$i*86400); //每隔一天赋值给数组
                        }
                    }else{
                        $beginThismonth = strtotime($startDateTime." 00:00:00");
                        $endThismonth = strtotime($endDateTime)+16*60*60-1;
                        $datetime1 = date_create($startDateTime);
                        $datetime2 = date_create($endDateTime);
                        $interval = date_diff($datetime1, $datetime2);
                        $dateNum = $interval->format('%a')+1;
                        for($i=0;$i<$dateNum;$i++) {
                            $arrayDate[] = date('Y-m-d',$beginThismonth+$i*86400); //每隔一天赋值给数组
                        }
                    }

                }
                //根据userid获取所有的考勤记录
                $userids = array_column($userLists,'id');
                $userids = implode(',',$userids);
                $attendancerecordCondition = " memberId in ($userids) and isDelete=0 and UNIX_TIMESTAMP(sureDate)>={$beginThismonth} and UNIX_TIMESTAMP(sureDate)<={$endThismonth}";
                $attendancerecordLists = $attendancerecordModel->select($attendancerecordCondition)->items;
                if ($attendancerecordLists){
                    $attendancerecordList = [];
                    foreach ($attendancerecordLists as $arLK=>$arlV){
                        $attendancerecordList[$arlV['memberId']][$arlV['sureDate']][] =  [
                            'id'=>$arlV['id'],
                            'leaveIn'=>$arlV['leaveIn'],
                            'leaveInId'=>$arlV['leaveInId'],
                            'no'=>$arlV['no'],
                            'clockinType'=>$arlV['clockinType'],
                            'clockinNum'=>$arlV['clockinNum'],
                            'clockinTime'=>$arlV['clockinTime'],
                        ];
                    }
                }else{
                    $attendancerecordList = [];
                }
                $attendancegroup = " isDelete= 0 and atd_attendance_group.platformId={$platformId}";
                $appadminuser = new model_lhbase_appadminuser();
                $appadminuserInfo = $appadminuser->selectOne("id={$adminUserId} and characters='zg' and unitsId=0");
//        print_r($adminUserId);die;
                if (!$appadminuserInfo){
                    $adminUserIdgroupId = new model_attendance_adminuserattendancegroup();
                    $attendancegroupIds = $adminUserIdgroupId->select(" adminUserId = {$adminUserId} ",'attendancegroupId')->items;

                    if ($attendancegroupIds){
                        $attendancegroupIds = array_column($attendancegroupIds,'attendancegroupId');
                        $attendancegroupIds = implode(',',$attendancegroupIds);
                        $attendancegroup .= " and atd_attendance_group.id in ({$attendancegroupIds}) ";
                    }else{
                        $result->message = "暂无数据";
                        $result->code = 200;
                        $result->data = [];
                        $result->counts = 0;
                        return $result;
                    }
                }
                //查询出平台下所有考勤组
                $attendancegroupList = $attendancegroupModel->select($attendancegroup)->items;
                if ($attendancegroupList)$attendancegroupList = $serviceGlobalsModel->setArrKeyId($attendancegroupList);
                $userAttendancegroupJoin = array('atd_attendance_group_user as aagu' => 'aagu.agId=atd_attendance_group.id');
                $userAttendancegroupList = $attendancegroupModel->select(
                    "  atd_attendance_group.isDelete= 0 and atd_attendance_group.platformId={$platformId} and aagu.type=1 and aagu.type<>2",
                    'aagu.memberId id,aagu.agId,atd_attendance_group.title,atd_attendance_group.id agId',
                    '',
                    '',
                    $userAttendancegroupJoin
                )->items;
                if ($userAttendancegroupList)$userAttendancegroupList = $serviceGlobalsModel->setArrKeyId($userAttendancegroupList);

                $attendancerecord = new model_attendance_attendancerecord();
                $leaverecordModel = new model_attendance_approvalprocessleaverecord();
                $replacementrecordModel = new model_attendance_approvalprocesscardreplacementrecord();
                if ($arrayDate){
                    $arrayDate = implode("','",$arrayDate);
                    $arrayDate = "'".$arrayDate."'";
                }else{
                    $arrayDate = 1;
                }
                foreach ($userLists as $key=>$valus){
                    $userStatisticsInfos[$valus['id']]['id'] = $valus['id'];
                    $userStatisticsInfos[$valus['id']]['realName'] = $valus['realName'];
                    $userStatisticsInfos[$valus['id']]['positionName'] = $valus['positionName'];
                    $userStatisticsInfos[$valus['id']]['unitsName'] = isset($UnitsList[$valus['unitId']])?$UnitsList[$valus['unitId']]['title']:"";//@@
                    $userStatisticsInfos[$valus['id']]['upLevelNnitsName'] = (isset($UnitsList[$valus['unitId']]) && isset($UnitsList[$UnitsList[$valus['unitId']]['pid']]))?$UnitsList[$UnitsList[$valus['unitId']]['pid']]['title']:"本单位";
                    $userStatisticsInfos[$valus['id']]['attendanceGroupName'] = isset($userAttendancegroupList[$valus['id']])?$userAttendancegroupList[$valus['id']]['title']:"未添加考勤组";//@@

                    $condition ="memberId = {$valus['id']} and sureDate in ({$arrayDate}) ";
                    $field = "sum(if((no=2 && clockinType=1),1,0)) as upMissCard,sum(if((no=2 && clockinType=2),1,0)) as downMissCard,sum(if(leaveIn=2,1,0)) as `leave`,sum(if((abnormalIdentityIs=2 or abnormalCoordinateIs=2),1,0)) as abnormal,sum(if(abnormal=1,1,0)) as late,sum(if(abnormal=2,1,0)) as leavEarly,sum(if(absenteeism>=1,1,0)) as completion";
                    $lists = $attendancerecord->selectOne($condition,$field);
                    foreach ($recordings as $key=>$value){
                        $onTimeList = [];
                        $daysNum = $dateNum;
                        if ($key=="onTime"){//
                            $onTimeList =  $attendancerecord->select(
                                " memberId = {$valus['id']} and sureDate in ({$arrayDate}) and absenteeism=2 and abnormal=0 and no=1 and leaveIn=1",
                                "id,sureDate,sureTime,count(id) num"
                            )->items;
                            $recordings['onTime'] = $onTimeList?$onTimeList[0]['num']:0;
                        }
                        elseif ($key=="daysNum"){
                            $undate = strtotime($endDateTime);
                            //根据用户ID获取考勤天数
                            $groupmemberrecordInfo = $groupmemberrecordModel->selectOne("memberIds like '%{$valus['id']}%' and addTime<={$undate} order by id  desc");

                            if (!$groupmemberrecordInfo){//当天没有班次添加
                                $recordings['daysNum'] = 0;
                            }else {
//                                $dateNum 选择日期总天数
                                $workdayKey = unserialize($groupmemberrecordInfo['workday']);
                                $holidayKey = $this->arrayDateToKey(unserialize($groupmemberrecordInfo['holiday']));
                                $specialWorkdayKey = $this->arrayDateToKey(unserialize($groupmemberrecordInfo['specialWorkday']));
                                $arrayDateX = explode(',',$arrayDate);
                                foreach ($arrayDateX as $dK=>$dV){
                                    $dV = strtotime(str_replace("'",'',$dV));
                                    $wDate = date('w',$dV);
                                    if ($wDate==0){
                                        $wDate=7;
                                    }
                                    if (in_array($wDate,$workdayKey)){//选择的日期为工作日 正常情况下需要打卡
                                        //判断当天是否为节假日
                                        if (in_array($wDate,$holidayKey)){//是节假日不需要打卡
                                            //判断当前日期 是否属于特殊工作日
                                            if (!in_array($wDate,$specialWorkdayKey)){//选择日期为特殊工作日 不是特殊工作日才允许不打卡
                                                $daysNum = $daysNum-1;//节假日
                                            }
                                        }
                                    }else{//休息日 本身不需要打卡 但是有特殊工作日时需求打卡
                                        if (in_array($wDate,$specialWorkdayKey)){//选择日期为特殊工作日

                                        }elseif (in_array($wDate,$holidayKey)) {//是节假日不需要打卡
                                            $daysNum = $daysNum-1;//节假日
                                        } else{
                                            $daysNum = $daysNum-1;//节假日
                                        }
                                    }
                                }
                                $recordings['daysNum'] = $daysNum;
                            }
                        }
                        elseif ($key=="completion"){
                            $completion = 0;
                            $completionList =$attendancerecord->select(
                                "memberId = {$valus['id']} and sureDate in ({$arrayDate}) and absenteeism>=1","id,memberId,clockinTime,sureTime,sureDate,clockinType")->items;

                            foreach ($completionList as $completionK=>$completionV){
                                if ($completionV['clockinType']==1){//1上班打卡 2下班打卡
                                    $completion += $completionV['clockinTime']-strtotime($completionV['sureDate']." ".$completionV['sureTime']);
                                }else{
                                    $completion += strtotime($completionV['sureDate']." ".$completionV['sureTime'])-$completionV['clockinTime'];
                                }
                            }
                            $completion = $completion>0?$serviceGlobalsModel->secsToStrws($completion):0;
                            $recordings['completion'] = $completion;
                        }
                        elseif ($key=="field"){
                            $fieldS = 0;
                            $fieldLists =$attendancerecord->select(
                                "memberId = {$valus['id']} and sureDate in ({$arrayDate}) and isGo=2","id,sureDate")->items;
                            if ($fieldLists)$fieldS = count(array_unique(array_column($fieldLists,'sureDate')));
                            $recordings['field'] = $fieldS;
                        }
                        elseif ($key=="clockinNum"){
                            $onTimeList =  $attendancerecord->select(
                                " memberId = {$valus['id']} and sureDate in ({$arrayDate}) and abnormalCoordinateIs=1 and abnormalIdentityIs=1 and absenteeism=2 and abnormal=0 and no=1 and leaveIn=1",
                                "id,count(id) num"
                            )->items;
                            $clockinNum = $onTimeList?$onTimeList[0]['num']:0;
                            $recordings['clockinNum'] = $clockinNum;
                        }
                        elseif ($key=="leave" || $key=="YearLeave" || $key=="nursingLeave" || $key=="casualLeave" || $key=="maternityLeave" || $key=="maritalLeave" || $key=="funeralLeave" ){
                            $leaveTypes = array("事假","年假","事假","调休","产假","婚假","丧假");
//                            请假类型 默认为0 1年假 2事假 3调休 4产假 5婚假 6丧假
//'YearLeave' 年假 'casualLeave' 事假 'maternityLeave' 产假  'maritalLeave' 婚假 'funeralLeave' 丧假
                            foreach ($leaveTypes as $leaveK=>$leaveValue){
                                switch ($leaveK){
                                    case 1:
                                        $onTimeList =  $leaverecordModel->select(
                                            "leaveType = {$leaveK} and memberId = {$valus['id']} and startTime>$beginThismonth and endTime<$endThismonth and status=2",
                                            "id,count(*) num"
                                        )->items;
                                        $recordings['YearLeave'] = !empty($onTimeList['num'])?$onTimeList['num']:0;//年假
                                        break;
                                    case 2:
                                        $onTimeList =  $leaverecordModel->select(
                                            "leaveType = {$leaveK} and memberId = {$valus['id']} and startTime>$beginThismonth and endTime<$endThismonth and status=2",
                                            "id,count(*) num"
                                        )->items;
                                        $recordings['casualLeave'] = !empty($onTimeList['num'])?$onTimeList['num']:0;//事假
                                        break;
                                    case 3://调休

                                        break;
                                    case 4:
                                        $onTimeList =  $leaverecordModel->select(
                                            "leaveType = {$leaveK} and memberId = {$valus['id']} and startTime>$beginThismonth and endTime<$endThismonth and status=2",
                                            "id,count(*) num"
                                        )->items;
                                        $recordings['maternityLeave'] = !empty($onTimeList['num'])?$onTimeList['num']:0;//产假
                                        break;
                                    case 5:
                                        $onTimeList =  $leaverecordModel->select(
                                            "leaveType = {$leaveK} and memberId = {$valus['id']} and startTime>$beginThismonth and endTime<$endThismonth and status=2",
                                            "id,count(*) num"
                                        )->items;
                                        $recordings['maritalLeave'] = !empty($onTimeList['num'])?$onTimeList['num']:0;//婚假
                                        break;
                                    case 6:
                                        $onTimeList =  $leaverecordModel->select(
                                            "leaveType = {$leaveK} and memberId = {$valus['id']} and startTime>$beginThismonth and endTime<$endThismonth and status=2",
                                            "id,count(*) num"
                                        )->items;
                                        $recordings['funeralLeave'] = !empty($onTimeList['num'])?$onTimeList['num']:0;//丧假
                                        break;
                                    case 7:
                                        $onTimeList =  $leaverecordModel->select(
                                            "leaveType = {$leaveK} and memberId = {$valus['id']} and startTime>$beginThismonth and endTime<$endThismonth and status=2",
                                            "id,count(*) num"
                                        )->items;
                                        $recordings['nursingLeave'] = !empty($onTimeList['num'])?$onTimeList['num']:0;//丧假
                                        break;
                                }
                            }
                        }
                        else
                        {
                            $recordings[$key] = $lists[$key]?$lists[$key]:0;
                        }
                    }
                    $userStatisticsInfos[$valus['id']]['recordings'] = $recordings;//@@
                }
//                    print_r(json_encode($userStatisticsInfos));die;
                $result->data = [[json_encode($userStatisticsInfos)]];
                $result->message ='成功';
                $result->code = 200;
                $result->counts = $count;
            }else{
                $result->data = [[]];
                $result->message ='成功';
                $result->code = 200;
                $result->counts = $count;
            }

        }
        catch(Exception $e){
            $result->message = '异常';
        }

        return $result;
    }

    //array [2018-02-11?@(春节(补))','2018-02-11?@(清明节(补))','2018-02-11?@(春节(补))']
    private function arrayDateToKey($array){
        if (!is_array($array))return [];
        $dateArray = [];
        foreach ($array as $key=>$value){
            $dates = explode('?@',$value);
            $dateArray[] =$dates[0];
        }
        return $dateArray;
    }


    public function getFaceInfoNum(AdminStatisticsDTO $AdminStatisticsDTO){

        $data = $AdminStatisticsDTO->data ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->data) :[];
        $platformId = $AdminStatisticsDTO->platformId ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->platformId) :0;

        #接受参数

        $adminUserId = $data['adminUserId']?$data['adminUserId']:0;

        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        $result->counts = 0;
        if(empty($platformId)){$result->message = "参数不正确"; return $result;}

        try{
            $userStatisticsInfos = [];
            $violationModel            = new model_attendance_violation();
            $num = $violationModel->selectOne("platformId = {$platformId}","count(id) num");
            $num = $num?$num['num']:0;
            $result->data = [[$num]];
            $result->message ='成功';
            $result->code = 200;
        }catch(Exception $e){
            $result->code = 400;
            $result->message = '异常';
        }

        return $result;
    }
}
